package org.example.servicelogin.security;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.model.manage.bean.po.security.*;
import org.example.servicelogin.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysPermissionsMapper sysPermissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<User> list = userMapper.selectList(new QueryWrapper<User>().eq(username != null, "account", username));
        if(list.isEmpty()) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        List<UserRole> UR = new ArrayList<>();
        for(User user : list) {
            UserRole temp = userRoleMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
            if (temp != null)  UR.add(temp);
        }

        List<SysRole> roles = new ArrayList<>();
        for(UserRole ur : UR) {
            SysRole temp = sysRoleMapper.selectOne(new QueryWrapper<SysRole>().eq("id", ur.getRoleId()));
            if(temp != null) roles.add(temp);
        }

        List<RolePermission> RP = new ArrayList<>();
        for(SysRole role : roles) {
            List<RolePermission> temp = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().eq("role_id", role.getId()));
            if (temp != null) RP.addAll(temp);
        }

        List<SysPermissions> permissions = new ArrayList<>();
        for(RolePermission rp : RP) {

            SysPermissions temp = sysPermissionMapper.selectOne(new QueryWrapper<SysPermissions>().eq("id", rp.getPermissionId()));
            if (temp != null) permissions.add(temp);
        }

        User u = list.get(0);


        return new MyUserDetails(u, roles, permissions);
    }
}
